package com.zbbt.sportslottery.ui.activity;

import java.io.IOException;
import java.util.Vector;

import android.content.pm.ActivityInfo;
import android.content.res.AssetFileDescriptor;
import android.graphics.Bitmap;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.os.Handler;
import android.os.Vibrator;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;

import com.google.gson.JsonObject;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.Result;
import com.zbbt.sportslottery.R;
import com.zbbt.sportslottery.app.Constant;
import com.zbbt.sportslottery.app.ServerConfig;
import com.zbbt.sportslottery.bean.HuoDongQuanData;
import com.zbbt.sportslottery.net.TypeGsonHttpHandler;
import com.zbbt.sportslottery.net.TypeResultHttpHandler;
import com.zbbt.sportslottery.net.ZbHttpClient;
import com.zbbt.sportslottery.ui.fragment.SaoYiSaoFragment;
import com.zbbt.sportslottery.ui.widget.saoyisao.CameraManager;
import com.zbbt.sportslottery.ui.widget.saoyisao.InactivityTimer;
import com.zbbt.sportslottery.ui.widget.saoyisao.MessageIDs;
import com.zbbt.sportslottery.ui.widget.saoyisao.SaoyiSaofragmentHandler;
import com.zbbt.sportslottery.ui.widget.saoyisao.ViewfinderView;
import com.zbbt.sportslottery.util.DialogUtil;
import com.zbbt.sportslottery.util.SharePreferUtil;
import com.zbbt.sportslottery.util.TimeUtil;
import com.zbbt.sportslottery.util.ToastUtil;
import com.zbbt.sportslottery.util.DialogUtil.OnshowUserListener;

public class SaoYiSaoActivity extends SimpleBaseActivity implements Callback {
	private ViewfinderView viewfinderView;
	private CameraManager cameraManager;// 二维码中的照相机功能处理
	private InactivityTimer inactivityTimer;// 这是一个在android2.3及以上系统下运行并开发的android二维码扫描软件
	private SaoyiSaofragmentHandler handler;
	private Vector<BarcodeFormat> decodeFormats;
	private String characterSet;
	private SurfaceView surfaceView;
	private MediaPlayer mediaPlayer;
	private boolean playBeep;
	private boolean hasSurface;
	private boolean vibrate;
	private String couponNum;// 体验券兑换码
	private int tiYanQuanId = 0;

	public SaoYiSaoActivity() {}

	@Override
	protected void onActivityCreated(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		setContentView(R.layout.activity_saoyisao);
	}

	@Override
	protected void initView() {
		// TODO Auto-generated method stub
		surfaceView = (SurfaceView) findViewById(R.id.preview_view);
		viewfinderView = (ViewfinderView) findViewById(R.id.viewfinder_view);
		Window window = this.getWindow();
		window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);// 设置高亮
		hasSurface = false;
		inactivityTimer = new InactivityTimer(this);
	}

	@Override
	protected void setListener() {

	}

	@Override
	protected void onClickEvent(View v) {
		switch (v.getId()) {
		case R.id.tv_right:
			goActivity(EXChangeActivity.class);
			break;

		default:
			break;
		}
	}

	@Override
	protected void initData() {

	}

	@Override
	public void onResume() {
		super.onResume();
		// 设置屏幕为竖屏
		if (this.getRequestedOrientation() != ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) {
			this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
		}
		if (cameraManager == null) {// 重复的new会出现崩溃状况
			cameraManager = new CameraManager(this.getApplication());
		}
		viewfinderView.setCameraManager(cameraManager);
		SurfaceHolder surfaceHolder = surfaceView.getHolder();
		if (hasSurface) {
			initCamera(surfaceHolder);
		} else {
			surfaceHolder.addCallback(this);
			surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
		}
		decodeFormats = null;
		characterSet = null;
		playBeep = true;

		// 如果当前是铃音模式，则继续准备下面的
		// 蜂鸣提示音操作，如果是静音或者震动模式。就不要继续了。因为用户选择了无声的模式，我们就也不要出声了。
		AudioManager audioService = (AudioManager) this.getSystemService(this.AUDIO_SERVICE);
		if (audioService.getRingerMode() != AudioManager.RINGER_MODE_NORMAL) {
			playBeep = false;
		}

		initBeepSound();
		vibrate = true;
	}

	@Override
	public void onPause() {
		super.onPause();
		if (handler != null) {
			handler.quitSynchronously();
			handler = null;
		}
		cameraManager.closeDriver();
		hasSurface = true;

	}

	@Override
	public void onDestroy() {
		inactivityTimer.shutdown();
		super.onDestroy();
	}

	/**
	 * 
	 * @MethodName: initBeepSound
	 * @Description: 初始化声音
	 * @author: yangwenquan
	 * @date: 2015年3月2日 下午4:49:54 void
	 */
	private void initBeepSound() {
		if (playBeep && mediaPlayer == null) {
			this.setVolumeControlStream(AudioManager.STREAM_MUSIC);
			mediaPlayer = new MediaPlayer();
			mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
			mediaPlayer.setOnCompletionListener(beepListener);
			try {
				AssetFileDescriptor fileDescriptor = this.getAssets().openFd("qrbeep.ogg");
				this.mediaPlayer.setDataSource(fileDescriptor.getFileDescriptor(),
						fileDescriptor.getStartOffset(), fileDescriptor.getLength());
				this.mediaPlayer.setVolume(0.1F, 0.1F);
				this.mediaPlayer.prepare();
			} catch (IOException e) {
				this.mediaPlayer = null;
			}
		}
	}

	/**
	 * 声音完成后到另一个列队
	 */
	private final OnCompletionListener beepListener = new OnCompletionListener() {
		public void onCompletion(MediaPlayer mediaPlayer) {
			mediaPlayer.seekTo(0);
		}
	};

	/**
	 * 
	 * @MethodName: initCamera
	 * @Description: 初始化照相机
	 * @author: yangwenquan
	 * @date: 2015年3月2日 下午4:10:41
	 * @param surfaceView
	 *            void
	 */
	private void initCamera(SurfaceHolder surfaceHolder) {
		try {
			cameraManager.openDriver(surfaceHolder);// 启动相机（需权限）
		} catch (IOException e) {
			e.printStackTrace();
		} catch (RuntimeException e) {
			return;
		}
		if (handler == null) {
			handler = new SaoyiSaofragmentHandler(this, decodeFormats, characterSet);
		}
	}

	@Override
	public void surfaceCreated(SurfaceHolder holder) {
		if (!hasSurface) {
			hasSurface = true;
			initCamera(holder);
		}
	}

	@Override
	public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

	}

	@Override
	public void surfaceDestroyed(SurfaceHolder holder) {
		hasSurface = false;
	}

	public void handleDecode(Result obj, Bitmap barcode) {
		inactivityTimer.onActivity();
		playBeepSoundAndVibrate();
		showResult(obj, barcode);
	}

	/**
	 * 
	 * @MethodName: showResult
	 * @Description: 扫描结果
	 * @author: yangwenquan
	 * @date: 2015年3月2日 下午5:09:17
	 * @param obj
	 * @param barcode
	 *            void
	 */
	private void showResult(Result rawResult, Bitmap barcode) {
		couponNum = rawResult.getText();
		if (couponNum.equals("")) {
			ToastUtil.showShort("扫描失败，点击右上角直接输入兑换号!");
			restartPreviewAfterDelay(5L);
		} else {
			if (couponNum.contains("http")) {
				// Intent intent = new Intent(context,
				// GameDataActivity.class);
				// intent.putExtra("Url", couponNum);
				// intent.putExtra("Title", "二维码详情");
				// startActivity(intent);
			}
			httpData1();
		}
	}

	// TODO 未完成
	private void httpData1() {
		JsonObject jsonObject = new JsonObject();
		jsonObject.addProperty("couponNum", couponNum);
		ZbHttpClient.postNewApi(ServerConfig.API_HDQXQ, jsonObject,
				new TypeGsonHttpHandler<HuoDongQuanData>() {

					@Override
					public void onSuccess(HuoDongQuanData data) {
						String statusStr = null;
						if (data != null) {
							if (data.getStatus() == 1) {
								statusStr = "未使用";
							} else if (data.getStatus() == 2) {
								statusStr = "已使用";
							} else if (data.getStatus() == 3) {
								statusStr = "已过期";
							}
							tiYanQuanId = data.getId();
							String name = data.getCouponName();
							int price = data.getPrice();
							final String couponNum = data.getCouponNum();
							String getExpire_time = TimeUtil.getTimeDate(data.getEndEffectiveTime());
							DialogUtil.showUserHDQDialog(SaoYiSaoActivity.this, name, price + "", couponNum,
									getExpire_time, statusStr, new OnshowUserListener() {

										@Override
										public void onPositiveButtonClick() {
											restartPreviewAfterDelay(0L);
										}

										@Override
										public void onNegativeButtonClick() {
											// 请求
											httpData();
											restartPreviewAfterDelay(0L);
										}

									});
						} else {
							restartPreviewAfterDelay(0L);
							ToastUtil.showLong("兑换码有误!!!");
						}
					}

					@Override
					public void onFailure(String errorCode, String errorMsg) {
						ToastUtil.showLong(errorMsg);
						restartPreviewAfterDelay(5L);
					}
				});
	}

	private void httpData() {
		JsonObject jsonObject = new JsonObject();
		String userId = SharePreferUtil.getString(Constant.USER_ID, "");
		jsonObject.addProperty("couponNum", couponNum);
		jsonObject.addProperty("userId", userId);
		jsonObject.addProperty("couponId", tiYanQuanId);
		ZbHttpClient.postNewApi(ServerConfig.API_TYQDH, jsonObject, new TypeResultHttpHandler() {

			@Override
			public void onSuccess() {
				ToastUtil.showLong("兑换成功");
			}

			@Override
			public void onFailure(String errorCode, String errorMsg) {
				ToastUtil.showLong(errorMsg);
			}
		});
	}

	/**
	 * 
	 * @MethodName: restartPreviewAfterDelay
	 * @Description: 延迟以后，重新开始
	 * @author: yangwenquan
	 * @date: 2015年3月2日 下午5:14:00
	 * @param delayMS
	 *            void
	 */
	public void restartPreviewAfterDelay(long delayMS) {
		if (handler != null) {
			handler.sendEmptyMessageDelayed(MessageIDs.restart_preview, delayMS);
		}
	}

	private static final long VIBRATE_DURATION = 200L;

	/**
	 * 
	 * @MethodName: playBeepSoundAndVibrate
	 * @Description: 声音和震动
	 * @author: yangwenquan
	 * @date: 2015年3月2日 下午5:07:32 void
	 */
	private void playBeepSoundAndVibrate() {
		if (playBeep && mediaPlayer != null) {
			mediaPlayer.start();
		}
		if (vibrate) {
			Vibrator vibrator = (Vibrator) this.getSystemService(this.VIBRATOR_SERVICE);
			vibrator.vibrate(VIBRATE_DURATION);
		}
	}

	public void drawViewfinder() {
		viewfinderView.drawViewfinder();

	}

	public Handler getHandler() {
		return handler;
	}

	public ViewfinderView getViewfinderView() {
		return viewfinderView;
	}

	public CameraManager getCameraManager() {
		return cameraManager;
	}

}
